/*
 * CS_GACHYA_BOX.cpp
 *
 *  Created on: 2013. 6. 13.
 *      Author: the2
 */

#include "../../Command.h"
#include "../../User.h"
#include "../../NLogic/Static.h"
#include "../../NLogic/SocialInfo.h"
#include "../../NLogic/Function.h"
#include "../../NResource/Static.h"
#include "../../Proxy.h"
#include "../../../../protocol/iFriends.h"
#include "../../NLogic/Reward.h"

namespace ProjectZ { namespace NCommand {

void
SendFailGachyaBox(User * pUser, int16_t result)
{
	::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
	* pAck << result
			<< static_cast<uint8_t>(0)
			<< static_cast<uint16_t>(0)
			<< static_cast<uint8_t>(0);
	pAck->MakePacket(CMD_SC_GACHYA_BOX);
	pUser->Send(pAck);
}
/*
// 뽑기 상자
ZNO_CS_GACHYA_BOX	0x2802
{

}

ZNO_SC_GACHYA_BOX	0x2803
{
	s16	s16ack;
	u8	u8sheet_type;	// 시트 타입
	u16	u16tid;			// 테이블 아이디
	u8	u8count			// 개수
}
*/
void Command::CS_GACHYA_BOX(User * pUser, ::Network::Packet * pPacket)
{
	PREPARE_PACKET;

	GachyaBoxSyn msg;

	NResource::BalanceResource * balanceResource = NResource::Static::InstancePtr()->GetBalance();
	msg.box_open_point = balanceResource->GetValue(pUser, EM_FRIEND_POINT_MAX);

	if(pUser->GetSocialInfo()->GetData()->_heart_count < msg.box_open_point)
	{
		SendFailGachyaBox(pUser, ACK_POINT_IS_LACKING);
		return;
	}

	NLogic::Reward::Data * data = pUser->GetReward()->GetData(NLogic::Reward::RewardType::FRIENDSHIP_BOX_REWARD);

	time_t curtime = time(NULL);

	TESTLOG("%s, initCurTime=%d FRIENDSHIP_BOX_REWARD reg_date=%d", __FUNCTION__,
			static_cast<uint64_t>(NLogic::NFunction::GetDailyInitTime(curtime)),
					pUser->GetUserInfo().array_Slot[NLogic::Reward::RewardType::FRIENDSHIP_BOX_REWARD].reg_date);

	if (static_cast<uint64_t>(NLogic::NFunction::GetDailyInitTime(curtime))
			> pUser->GetUserInfo().array_Slot[NLogic::Reward::RewardType::FRIENDSHIP_BOX_REWARD].reg_date)
	{
		// 하루가 지나면 상자를 열수 있는 횟수 초기화
		data->_value = 0;
	}

	// 하루에 상자를 열수 있는 횟수 20회
	if (20 <= data->_value)
	{
		SendFailGachyaBox(pUser, ACK_FRIENDSHIP_BOX_OPEN_OVER_FLOW);
		return;
	}

	NResource::FriendshipBoxResource * pFriendShipBox = NResource::Static::InstancePtr()->GetFriendshipBox();
	if(NULL == pFriendShipBox)
	{
		DEBUGLOG("CS_GACHYA_BOX [NULL == pFriendShipBox] userseq = %d", pUser->GetUserSeq());
		SendFailGachyaBox(pUser, ACK_UNKNOWN_ERROR);
		return;
	}

	NResource::FriendshipBoxData *pFriendShipBoxData = pFriendShipBox->GetFly(pUser);
	if (NULL == pFriendShipBoxData)
	{
		DEBUGLOG("CS_GACHYA_BOX [NULL == pFriendShipBoxData] userseq = %d", pUser->GetUserSeq());
		SendFailGachyaBox(pUser, ACK_UNKNOWN_ERROR);
		return;
	}

	int totalRate = pFriendShipBoxData->GetTotalRate();
	int accRate = 0;
	int randRate = rand() % totalRate;

	auto iter = pFriendShipBoxData->GetTree().begin();
	for(; iter != pFriendShipBoxData->GetTree().end(); ++iter)
	{
		accRate += iter->second->_RATE;

		if (randRate < accRate)
			break;
	}
	DEBUGLOG("CS_GACHYA_BOX totalRate = %d randRate = %d accRate = %d userseq = %d", totalRate, randRate, accRate, pUser->GetUserSeq());

	if (iter == pFriendShipBoxData->GetTree().end())
	{
		DEBUGLOG("CS_GACHYA_BOX [iter == pFriendShipBoxData->GetTree().end()] userseq = %d", pUser->GetUserSeq());
		SendFailGachyaBox(pUser, ACK_UNKNOWN_ERROR);
		return;
	}

	NLogic::MailBox::Mail::Data clsMailData;
	clsMailData.send_user_seq		= 0;
	clsMailData.send_user_nickname	= "GAMEVIL";
	clsMailData.recv_user_seq		= pUser->GetUserSeq();

	std::string mailMessage;
	mailMessage.append("[").append(NResource::Static::InstancePtr()->GetMailMessageResource()->GetMessageFriendshipReward()).append("]!N");
	clsMailData.message				= mailMessage.c_str();
	clsMailData.message.Append(iter->second->_ITEM_NAME.c_str(), iter->second->_ITEM_NAME.Len());
	clsMailData.gift_status			= EM_GIFT_ITEM;
	clsMailData.item.tid			= iter->second->_REWARD_TID;
	clsMailData.item.sub_type		= iter->second->_SHEET_TYPE;
	clsMailData.item.class_type		= -1;

	NResource::Static::InstancePtr()->GetItemResource()->setItemEffect(clsMailData.item);
	int sendMailCount	= 0;

	// 스택 아이템인 경우
	if (1 == NResource::Static::InstancePtr()->GetItemResource()->getItemStackType(clsMailData.item))
	{
		clsMailData.item.quantity	= iter->second->_COUNT;
		sendMailCount		= 1;
	}
	else
	{
		// 스택 아이템이 아닌 경우 하나씩 첨부하여 발송
		clsMailData.item.quantity	= 1;
		sendMailCount		= iter->second->_COUNT;
	}

	// 아이템 부가 정보 세팅
	if (false == NResource::Static::InstancePtr()->GetItemResource()->SetItemDataFromResource(pUser, clsMailData.item))
	{
		DEBUGLOG("%s : SetItemDataFromResource Fail!", __FUNCTION__);
		SendFailGachyaBox(pUser, ACK_DB_ERROR);
		return;
	}

	// 메일 발송
	for (int i = 0; i < sendMailCount; i++)
	{
		if (false == NLogic::NFunction::SendMail(pUser, clsMailData))
		{
			DEBUGLOG("%s : ITEM Mail Send Fail!!", __FUNCTION__);
			SendFailGachyaBox(pUser, ACK_DB_ERROR);
			return;
		}
	}

	data->_value++;
	pUser->GetUserInfo().array_Slot[NLogic::Reward::RewardType::FRIENDSHIP_BOX_REWARD].reg_date = curtime;
	pUser->FlushUserInfoCache();

	pUser->GetSocialInfo()->GetData()->_heart_count -= msg.box_open_point;
	if( 0 > pUser->GetSocialInfo()->GetData()->_heart_count )
		pUser->GetSocialInfo()->GetData()->_heart_count = 0;

	::ProjectZ::NProxy::SendFriendsServer(pUser->GetUserSeq(), msg);

	::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
	* pAck << static_cast<uint16_t>(ACK_OK)
			<< static_cast<uint8_t>(iter->second->_SHEET_TYPE)
			<< static_cast<uint16_t>(iter->second->_REWARD_TID)
			<< static_cast<uint8_t>(iter->second->_COUNT);

	pAck->MakePacket(CMD_SC_GACHYA_BOX);
	pUser->Send(pAck);
}

} /*NCommand*/ } /*ProjectZ*/

